<template>
  <div
    class="msg-item-warpper"
    :class="{ 'is-user': props.isUser }">
    <div
      class="avatar"
      :style="{ background: props.isUser ? '#2B3E6C' : '' }">
      <img :src="props.isUser ? userAvatar : robotAvatar" />
    </div>
    <div
      class="msg-content user-content"
      v-if="props.isUser">
      <div v-if="props.imgSrc && !props.message">
        <img
          :src="props.imgSrc"
          alt="" />
      </div>
      <div v-else>
        <div
          v-text="props.message"
          style="white-space: pre-wrap"></div>
      </div>
    </div>
    <div
      class="msg-content"
      v-else>
      <div
        class="markdown-body"
        :style="{ color: props.isFailed ? 'red' : '' }">
        <div
          v-html="renderMsg(props.message)"
          v-link-target-blank></div>
      </div>
      <div
        class="question-content"
        v-if="quesRecommend?.length">
        <div
          class="title"
          :style="{ marginBottom: isExpand ? 0 : '' }">
          <span>相关问题&nbsp;·&nbsp;{{ quesRecommend?.length }}</span>
          <el-icon
            v-if="!isExpand"
            @click="expandList"
            ><ArrowUp color="#fff"
          /></el-icon>
          <el-icon
            v-else
            @click="collapseList"
            ><ArrowDown color="#fff"
          /></el-icon>
        </div>
        <div
          class="ques-list"
          v-show="!isExpand">
          <div
            class="ques-item"
            @click="askQuestion(item)"
            v-for="(item, index) in quesRecommend"
            :key="index">
            <div>{{ index + 1 }}.&nbsp</div>
            <div>{{ item }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, onMounted, watch, computed } from 'vue'
  import robotAvatar from '@/assets/img/page/robotAvatar.png'
  import userAvatar from '@/assets/img/page/userAvatar.png'
  import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
  import { Marked } from 'marked'
  import { markedHighlight } from 'marked-highlight'
  import hljs from 'highlight.js'
  import 'highlight.js/styles/monokai.css'

  const emit = defineEmits(['askQuestion'])
  const { proxy } = getCurrentInstance()
  const props = defineProps({
    message: {
      type: [String, Number],
      default: ''
    },
    isUser: {
      type: Boolean,
      default: false
    },
    isTyping: {
      type: Boolean,
      default: false
    },
    imgSrc: {
      type: String,
      default: ''
    },
    isFailed: {
      type: Boolean,
      default: false
    }
  })
  // const quesRecommend = ref(null)
  const quesRecommend = ref([])
  const cursor = computed(() => {
    if (props.isTyping) {
      return "<span class='typing-indicator'></span>"
    } else {
      return ''
    }
  })
  const isExpand = ref(false)
  /* ========方法========= */
  const expandList = () => {
    isExpand.value = !isExpand.value
  }
  const collapseList = () => {
    isExpand.value = !isExpand.value
  }
  const askQuestion = ques => {
    emit('askQuestion', ques)
  }
  const renderMsg = rawString => {
    let resArr = rawString.split('<references')
    let questions = resArr[0] ? resArr[0].split('你可以继续这样问我:')[1] : ''
    quesRecommend.value = handleQuestions(questions)
    let mainContent =
      resArr[0]
        .split('你可以继续这样问我:')[0]
        .replace(/\\\\n/g, '\n')
        .replace(/\\n/g, '\n')
        .replace(/&nbsp;/g, ' ')
        .replace(/\\"/g, '"')
        .replace(/"\\/g, '"') + cursor.value
    const marked = new Marked(
      markedHighlight({
        langPrefix: 'hljs language-',
        highlight(code, lang, info) {
          const language = hljs.getLanguage(lang) ? lang : 'plaintext'
          return hljs.highlight(code, { language }).value
        }
      })
    )
    return marked.parse(mainContent)
  }
  const handleQuestions = questions => {
    if (questions) {
      // 去掉前后的换行符
      const trimmedStr = questions
        .replace(/\\\\n/g, '\n')
        .replace(/\\n/g, '\n')
        .replace(/&nbsp;/g, ' ')
        .replace(/\\"/g, '"')
        .replace(/"\\/g, '"')
        .trim()

      // // 使用正则表达式按问题分割
      const questionsArray = trimmedStr.split(/\n\d+\.\s*/).filter(part => part.trim() !== '')
      console.log(questionsArray)
      return questionsArray || []
    }
  }
  watch(
    () => props.message,
    (newVal, oldVal) => {},
    {
      deep: true,
      immediate: true
    }
  )
  onMounted(() => {})
</script>

<style scoped lang="scss">
  .msg-item-warpper {
    position: relative;
    margin-bottom: pxTvh(24);
    min-height: pxTvh(34);
    color: #cfdbfc;

    & > .avatar {
      display: flex;
      justify-content: center;
      align-items: center;
      width: pxTvw(32);
      min-width: pxTvw(32);
      height: pxTvw(32);
      margin-right: pxTvw(16);
      border-radius: pxTvw(8);
      overflow: hidden;
      position: absolute;
      top: 0;
      left: pxTvw(-48);
      background: linear-gradient(142deg, #b341ff 0%, #2275f0 65%, #01d5dd 100%);
      & > img {
        width: 80%;
        height: 80%;
      }
    }
    & > .msg-content {
      background: #1d2a4b;
      border-radius: pxTvw(8);
      padding: pxTvw(20);
      // white-space: pre-wrap;
      word-wrap: break-word; /* 长单词自动换行 */
      word-break: break-all; /* 长单词在任意位置换行 */
      overflow-wrap: break-word; /* 强制长单词在行末换行 */
      .question-content {
        width: 100%;

        transition: all 0.8s;
        & > .title {
          // color: rgba(207, 219, 252, 0.8);
          color: #fff;
          margin-bottom: pxTvh(16);
          display: flex;
          align-items: center;
          & > span {
            margin-right: pxTvw(8);
          }
          & > .el-icon {
            cursor: pointer;
          }
        }
        & > .ques-list {
          background-color: rgba(24, 35, 62, 1);
          color: #fff;
          padding: pxTvw(16);
          border-radius: pxTvw(8);

          & > .ques-item {
            display: flex;
            align-items: center;
            cursor: pointer;
            margin-bottom: pxTvh(8);
            height: pxTvh(20);
            line-height: pxTvh(20);
            & > div:last-child {
              width: 100%;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
          }
          & > .ques-item:last-child {
            margin-bottom: pxTvh(0);
          }
          & > .ques-item:hover {
            color: #2f65cc;
          }
        }
      }
    }
    & > .user-content {
      & > div {
        min-height: pxTvw(32);
        display: flex;
        align-items: center;
      }
      img {
        width: pxTvw(200);
        height: auto;
      }
    }
  }
  :deep(.markdown-body) {
    div {
      * {
        margin: pxTvh(8) 0;
      }
      a {
        color: #377dff;
        text-decoration: none;
      }
    }
    .typing-indicator {
      margin: pxTvh(0) pxTvw(0) pxTvh(2) pxTvw(6);
      width: pxTvh(6);
      height: pxTvh(6);
      background-color: #165dff;
      border-radius: 50%;
      animation: breathe 1s infinite ease-in-out;
      display: inline-block;
      transform-origin: center center;
    }
  }
  .is-user {
    & > .msg-content {
      background: transparent;
      padding: pxTvw(0);
    }
  }
  @keyframes breathe {
    0%,
    100% {
      transform: scale(1.4);
    }
    50% {
      transform: scale(1.2);
    }
  }
</style>
